<template>
	<view class="u-padding-left-32 u-padding-right-32 u-padding-bottom-32"> 
			<view v-for="(year,y) in yearList" :key="y" class="u-margin-bottom-20" :id="`month-`+year.monthNum">
				<!-- 月 -->
				<item-box :padding="22">
					<view class="text-bold box-title u-flex u-row-between u-m-b-50">
						<view>
							<!-- 显示当前item的月份 -->
							{{year.year}} <text class="u-font-32">/{{year.monthNum}}月</text>
						</view>
						<!-- 根据日期索引统计的展会列表 -->
						<view class="u-font-20 text-tips" v-if="exhibitionObj[year.month]">
							{{exhibitionObj[year.month].length}}场展会
						</view>
					</view>
					<view class="u-flex">
						<!-- 当前item的星期中文 -->
						<view v-for="(weekTxt,i) in weekList" :key="i" class="week-txt u-flex-1 u-text-center u-font-30 content-desc-item">
							{{weekTxt}}
						</view>
					</view>
					<view class="u-grid day-box">
						<!-- 当前item的日期 -->
						<view v-for="(month,m) in year.dayList" :key="m" class="u-margin-top-20" :class="{
							'is-show-flag':month.tagList&&month.tagList.length
						}">
							<!-- 判断当前日期对应的是星期几 -->
							<view class="day-num u-flex u-row-center">
								<text :class="{'current-day':month.isCurrentDay}" class=" u-flex u-row-center">{{month.dayNum || ''}}</text>
							</view>
							<view v-for="(tag,a) in month.tagList" :key="a" class="u-margin-top-10" :class="{
								'u-margin-left-20':tag.showName
							}" @click="tagClick(tag)">
								<!-- 这里需要根据是否参加过展会设置给show-tag背景色 -->
								<view class="show-tag" :class="{'show-tag-active':!tag.isEmpty&&tag.isWill,'show-tag-un-join':!tag.isEmpty&&!tag.isWill}"></view>
								<view class="city-name" :class="[tag.isWill?'text-color-txtTheme ':'text-tips',{'u-font-24':tag.name.length==2},{'u-font-20':tag.name.length==3},{'u-font-8':tag.name.length>=4}]">
									{{tag.showName&&tag.name ? tag.name.substr(0,4) : ''}}
								</view>
								<!-- <view class="city-name text-color-txtTheme">
									{{tag.name ? tag.name.substr(0,2) : '无'}}
								</view> -->
							</view>
						</view>
					</view>
				</item-box>
			</view>

			<view class="to-month" @click="toCurMonth" v-if="!showMonth && currentYear==realYear">
				<view><u-icon name="rili" size="40" custom-prefix="index-custom-icon" :color="currentThemeObj.primary"></u-icon></view>
				<view class="u-font-24 text-color-txtTheme">{{currentMonth}}月</view>
			</view>
			
			<view class="loading-box" v-if="showLoading">
				<u-loading :show="showLoading"></u-loading>
				<view>数据加载中...</view>
			</view>
	</view>
</template>

<script>
	import dayjs from 'dayjs'
	export default {
		props:{
			currentYear: {
				type: [Number,String],
				default: dayjs().format("YYYY")
			},
			calenderList:{
				type:Array,
				default:()=>([])
			}
		},
		data() {
			return {
				 //讲道理应该后台返回哪一年有展会 所以渲染的时候应该是渲染某一年的整年日历
				weekList: ['日', '一', '二', '三', '四', '五', '六'],
				exhibitionObj: {},
				currentMonth:1,//当前月份
				showLoading:true,
				showMonth:false,
				realYear:'',//当前年
			}
		},
		computed: {
			yearList(){
				const list = this.calenderList.sort((a,b)=>dayjs(a.beginTime).isBefore(b.beginTime) ? -1 : 1) // 先排序
				const renderList = this.returnRenderList(list) // 根据开始时间和结束时间生成时间线
				// this.loaded()
				return this.getYearList(renderList) // 返回当前年的数据
			},
		},
		mounted() {
			this.currentMonth = dayjs().format("M");
			this.$nextTick(()=>{
				setTimeout(()=>{
					this.toCurMonth();
					this.showLoading=false
					this.realYear = dayjs().format("YYYY");
				},100)
			})
		},
		created() {
			uni.$on('scrollViewListen',res=>{
				this.showMonth = res;
			})
		},
		destroyed() {
			uni.$off('scrollViewListen')
		},
		methods: {
			// //加载完成后通知上级组件
			// loaded(){
			// 	setTimeout(()=>{
			// 		this.$emit('loaded')
			// 	},400)
			// },
			toCurMonth(){
				const currentMonth = dayjs().format("M");
				const elementId = 'month-'+currentMonth
				const query = uni.createSelectorQuery();
				// console.log(query.select('#'+elementId))
				query.in(this).select('#'+elementId).boundingClientRect(data => {
					// console.log(data)
					this.$emit('getCurrentMonthElement',data)
				}).exec();
			},
			//返回当前年的日历数据
			getYearList(list){
				const year = this.currentYear
				// 遍历出1-12月的月份
				let monthNum = 1;
				const lastMonthNum = 13;
				let monthList = []
				//生成月
				while (monthNum < lastMonthNum) {
					monthList.push({
						monthNum,
						year
					})
					monthNum++;
				}
				//生成日
				monthList = monthList.map(item => {
					const month = `${year}-${item.monthNum}`;
					const dayList = [];
					const daysInMonth = dayjs(month).daysInMonth()
					let dayNum = 1;
					//获取这个月第一天是星期几 然后需要设置几个空盒子来完成渲染
					const startDayWeek = dayjs(month).startOf('month').format('d')
					let emptyDayNum = 0;
					//日期占位
					while (emptyDayNum < startDayWeek) {
						dayList.push({
							isEmpty: true
						})
						emptyDayNum++
					}
					// 日期
					while (dayNum <= daysInMonth) {
						const weekDay = dayjs(`${month}-${dayNum}`).format('d')
						const day = dayjs(`${month}-${dayNum}`).format('YYYY-MM-DD')
						const tagList = this.getCityTag(day,list); // 生成哪天应该展示色块或者占位的元素
						//判断当前日是不是今天
						const isCurrentDay = dayjs(`${month}-${dayNum}`).format('YYYY-MM-DD')===dayjs().format('YYYY-MM-DD')
						dayList.push({
							day,
							dayNum,
							weekDay,
							isCurrentDay,
							tagList
						})
						dayNum++;
					}
					return {
						dayList,
						month: dayjs(month).format('YYYY-MM'),
						year: item.year,
						monthNum: item.monthNum
					}
				})
				return monthList;
			},
			// //根据后台数据返回的开始结束时间处理时间线
			// /*思路：
			//  *	1.整理展会城市的开始时间结束时间:beginTime: '2021-11-22', endTime: "2021-12-05",
			//  * 需要整理为['2021-11-22','2021-11-23','2021-11-24','2021-11-25']
			//  */
			returnRenderList(list){
				const exhibitionObj = {};
				return list.map(val => {
					this.$set(val,'exhibitTimeList',[])
					val.exhibitTimeList.push({ // 开始时间直接设置
						// ...val,
						time: dayjs(val.beginTime).format('YYYY-MM-DD'),
						name: val.abbreviation || '',
						exhibitId:val.exhibitId,
						showName: true,// 只有第一个时间格子会显示城市名
					});
					//获取结束时间比开始时间多几天
					const daydiff = dayjs(val.endTime).diff(dayjs(val.beginTime), 'day')
					let dayStart = 1;
					while (dayStart < daydiff + 1) {
						//判断当天是不是周日 如果是则需要显示名称
						const timeDay = dayjs(val.beginTime).add(dayStart, 'day')
						const isMonthStartDay = dayjs(timeDay).startOf('month').format('YYYY-MM-DD')===timeDay.format('YYYY-MM-DD')
						const showName = dayjs(timeDay).format('d') == 0 || isMonthStartDay // 除了开始时间 每周日肯定是第一条数据 或者每个月的开始第一天（开始第一天会有空行所以有可能不是周末）
						val.exhibitTimeList.push({
							// ...val,
							time: timeDay.format('YYYY-MM-DD'),
							name: val.abbreviation || '',
							exhibitId:val.exhibitId,
							showName
						})
						dayStart++;
					}
					//根据开始结束时间统计当前月的展会数据
					const startMonth = dayjs(val.beginTime).format('YYYY-MM');
					const endMonth = dayjs(val.endTime).format('YYYY-MM');
					this.exhibitionObj = this.exhibitionList(startMonth, endMonth, val, exhibitionObj)
					//返回时间数组
					return val
				})
			},
			//根据开始结束时间统计当前月的展会数据
			exhibitionList(startMonth, endMonth, val, exhibitionObj) {
				//开始时间
				if (exhibitionObj.hasOwnProperty(startMonth)) { // 如果对象里面存在这个月 那么就直接push展会数据
					const flag = exhibitionObj[startMonth].some(item => item.exhibitId == val.exhibitId);
					!flag && exhibitionObj[startMonth].push(val)
				} else {
					exhibitionObj[startMonth] = [val] // 没有则直接添加
				}
				//结束时间
				if (exhibitionObj.hasOwnProperty(endMonth)) {
					const flag = exhibitionObj[endMonth].some(item => item.exhibitId == val.exhibitId);
					!flag && exhibitionObj[endMonth].push(val)
				} else {
					exhibitionObj[endMonth] = [val]
				}
				return exhibitionObj
			},
			/*
			1.先判断当前日有没有数据 如果有直接获取
			2.获取当前时间本星期的时间列表
			3.获取当前时间在哪个月
			4.过滤当前时间在哪些展会范围内
			5. 判断是否已经添加了展会到数组 如果添加了就操作到新数据 如果没有则需要占位
			 */
			getCityTag(day,exhibitList){
				let findDay = [];
				exhibitList.forEach(val => {
					// 判断当前显示的时间格子和时间列表匹配则返回数据 否则不返回 不返回当然就为空了
					const findTime = val.exhibitTimeList.find(val => val.time == day);
					findTime && findDay.push(findTime)
				})
				const weekDayList = this.getWeekList(day);//本周数据列表
				const time = dayjs(day).format('YYYY-MM'); // 获取当前月
				let list = this.exhibitionObj[time] || []; // 获取统计好的当前月的展会列表 如果后台有分好组的可以直接使用
				list = list.filter(val=>{
					const flag = weekDayList.some(item=>dayjs(val.beginTime).unix() <= dayjs(item).unix() && dayjs(val.endTime).unix() >= dayjs(item).unix())
					return flag
				})
				let filterList = []
				if(findDay.length&&list.length){
					list.forEach((val, index) => {
						const has = findDay.find(item => item.exhibitId === val.exhibitId)
						if (has) {
							// filterList = [...filterList,...findDay]
							// 判断当前时间的展会是否已经是过去式 如果是按照已经开始为灰色 就用val.beginTime 如果是 结束的展示灰色用val.endTime 
							// 如果当天时间之前的时间就用day 因为是今天之前 所以应该不包括今天
							const isWill = dayjs(day).isAfter(dayjs().subtract(1,'days'))
							const find = filterList.some(item => item.exhibitId === val.exhibitId)
							if(!find){
								filterList.push({
									...has,
									isWill
								})
							}
						} else {
							// const nextObj = list.find(item=>dayjs(item.beginTime).isAfter(dayjs(val.endTime)))
							const nextObj = list[index+1];
							if(nextObj){ // 得到下一次展会的数据 判断当前展会的结束时间加一天等不等于下一场展会的开始时间
								const endTime = dayjs(val.endTime).format('YYYY-MM-DD');
								// 如果下一条数据的开始时间在当前展会结束时间之前
								const isbeginAfter = dayjs(nextObj.beginTime).isAfter(dayjs(val.endTime)) 
								if(isbeginAfter){
									const findTime = nextObj.exhibitTimeList.find(val => val.time == day);
									const isWill = dayjs(day).isAfter(dayjs().subtract(1,'days'))
									const find = findTime&&filterList.some(item => item.exhibitId === findTime.exhibitId)
									find&&filterList.push({
										...findTime,
										isWill
									})
									// console.log(nextObj.abbreviation,val.abbreviation)
								}else{
									filterList.push({
										isEmpty: true, //是否显示色块
										name: val.abbreviation || ''
									})
									// console.log(nextObj.abbreviation,val.abbreviation,day)
								}
							}
							// filterList.push({
							// 	isEmpty: true, //是否显示色块
							// 	name: val.abbreviation
							// })
						}
					})
					findDay = filterList
				}
				return findDay
			},
			//返回一周内的时间列表
			getWeekList(day) {
				const currentDayWeekNum = dayjs(day).startOf('day').format('d') // 当前日期是星期几
				// let weekEndDay =  // 当前时间的星期六
				const startDay = dayjs(day).subtract(currentDayWeekNum, 'day').format("YYYY-MM-DD") // 周日
				const daydiff = 7
				let dayStart = 0;
				const weekDayList = []
				while (dayStart < daydiff) {
					const getDay = dayjs(startDay).add(dayStart, 'day').format('YYYY-MM-DD'); //当前周的日期列表
					weekDayList.push(getDay)
					dayStart++;
				}
				return weekDayList;
			},
			//色块点击
			tagClick(item){
				if(item.exhibitId){
					this.$u.route({
						url:'/pagesB/exhibitionCalender/exhibitionDetail',
						params:{
							id:item.exhibitId
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	.day-num {
		height: 70rpx;
	}

	.city-name {
		height: 55rpx;
		line-height: 55rpx;
	}

	.day-box {
		grid-template-columns: repeat(7, 14.3%)
	}

	.show-tag {
		width: 100%;
		height: 20rpx;
	}

	.show-tag-active {
		background-color: rgba($color: #765CFE, $alpha: 0.5)
	}
	.show-tag-un-join{
		background-color: #999999
	}
	.is-show-flag {
		background-color: #F0F1F5;
	}
	.current-day{
		width: 50rpx;
		height: 50rpx;
		background-color: var(--theme-color);
		border-radius: 50%;
		color: white;
	}
	.to-month{
		z-index: 9990;
		left: auto;
		right: 20rpx;
		bottom: 120rpx;
		width: 100rpx;
		height: 100rpx;
		background: #FCFCFC;
		box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(118, 92, 254, 0.4);
		border-radius: 50%;
		transition: opacity 0.5s;
		position: fixed;
		text-align: center;
		padding-top: 14rpx;
	}
	.loading-box{
		position: fixed;
    top: 40%;
    left: 0;
		right: 0;
		bottom: 0;
		// transform: translate3D(0px, 0px, 0px) !important;
		text-align: center;
		color: #999999;
		// display: flex;
		// justify-content: center;
    // align-items: center;
	}
	.u-font-8{
		font-size: 16rpx;
	}
</style>
